﻿using SAEA.Common;
using SAEA.MVC;
using KeydbCommand.Models;
using KeydbCommand.Libs;
using System.Diagnostics;
using System;

namespace KeydbCommand.Attr
{
    /// <summary>
    /// 验证并记录日志
    /// </summary>
    public class AuthAttribute : ActionFilterAttribute
    {
        Stopwatch _stopwatch;

        bool _isAdmin = false;

        public AuthAttribute(bool isEnabled)
        {

        }

        public AuthAttribute(bool isAdmin, bool isEnabled) : this(isEnabled)
        {
            _isAdmin = isAdmin;
        }


        public override bool OnActionExecuting()
        {
            _stopwatch = Stopwatch.StartNew();

            if (!HttpContext.Current.Request.Cookies.ContainsKey("keydb_uid"))
            {
                HttpContext.Current.Response.SetCached(new JsonResult(new JsonResult<string>() { Code = 3, Message = "当前操作需要登录！" }));

                HttpContext.Current.Response.End();

                return false;
            }
            if (_isAdmin)
            {
                var uid = HttpContext.Current.Request.Cookies["keydb_uid"].Value;
                var user = UserHelper.Get(uid);

                if (user == null)
                {
                    var cookie = HttpContext.Current.Request.Cookies["keydb_uid"];
                    cookie.Expires = DateTime.Now.AddDays(-1);
                    HttpContext.Current.Response.Cookies.Add("keydb_uid",cookie);
                    HttpContext.Current.Response.SetCached(new JsonResult(new JsonResult<string>() { Code = 3, Message = "当前操作需要登录！" }));

                    HttpContext.Current.Response.End();

                    return false;
                }

                if (user.Role != Role.Admin)
                {
                    HttpContext.Current.Response.SetCached(new JsonResult(new JsonResult<string>() { Code = 4, Message = "当前操作权限不足，请联系管理员！" }));

                    HttpContext.Current.Response.End();

                    return false;
                }
            }

            return true;
        }

        public override void OnActionExecuted(ref ActionResult result)
        {
            _stopwatch.Stop();

            LogHelper.Info(HttpContext.Current.Request.Url, HttpContext.Current.Request.Parmas, result, _stopwatch.ElapsedMilliseconds);
        }
    }
}
